import asyncio

from mirai import MessageEvent, Mirai

from robot_command.run_command import RunCommand
from robot_service.message_trigger import MessageTrigger
from robot_service.service_repository import ServiceRepository


class ServiceDispatcher:

    def __init__(self, bot: Mirai):
        self.__is_sleep = False
        self.__bot = bot
        self.__command_help = RunCommand()
        self.__service_repository = ServiceRepository(bot)
        self.__message_trigger = MessageTrigger(bot)

    async def message_push(self):
        """信息推送方法"""
        await asyncio.gather(self.__service_repository.dayly_poetry(), self.__service_repository.wpf_push())

    async def service_dispatcher(self, event: MessageEvent):
        try:
            # 消息捕获器
            is_triggered = await self.__message_trigger.keyword_capture(event)
            if is_triggered:
                return

            event_msg = str(event.message_chain)
            command = self.__command_help.get_service_func(str(event_msg))
            if command is None or command == '':
                return
            command_name = str(command.get('command_func_name'))
            command_param = str(command.get('command_func_param'))
            has_func = hasattr(ServiceRepository, command_name)

            if has_func:
                if self.__is_sleep is False or (command_name == 'bot_shutdown' or command_name == 'bot_startUp'):
                    if command_name == 'bot_shutdown':
                        self.__is_sleep = True
                    elif command_name == 'bot_startUp':
                        self.__is_sleep = False
                    # TODO 添加启动控制，可以只服务特定的群,记录每个群的机器人开关状态
                    service = getattr(self.__service_repository, command_name)
                    await service(command_param, event)
                else:
                    return
        except Exception as e:
            raise

